package com.af.security.auth.util.listener;

import com.af.security.auth.login.lock.LoginFailureCache;
import com.af.security.auth.login.service.AfUserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * @author : zhenyun.su
 * @common : 监听认证成功
 * 1. 触发清空缓存中记录失败次数
 * 2. 将账号密码认证， ldap认证及手机等不同方式，而返回不同认证数据，实现统一认证数据；
 * @since : 2020/6/24
 */

@Component
public class AfAuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> {
    private static final Logger logger = LoggerFactory.getLogger(AfAuthenticationSuccessEventListener.class);

    private LoginFailureCache loginFailureCache;
    private AfUserDetailsService userDetailsService;

    public AfAuthenticationSuccessEventListener(LoginFailureCache loginFailureCache, AfUserDetailsService afUserDetailsService) {
        this.loginFailureCache = loginFailureCache;
        this.userDetailsService = afUserDetailsService;
    }

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent authenticationSuccessEvent) {
        try{
            Authentication authentication = authenticationSuccessEvent.getAuthentication();
            String name = authentication.getName();
            Object principal = authentication.getPrincipal();



            logger.debug("authentication success, begin clear " + name + " LoginFailureCache");
            loginFailureCache.loginSucceeded(name);
        }catch(Exception e){
            logger.error("AuthenticationSuccessEvent failed: {}", e);
        }
    }
}
